package com.xz.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.annotation.DataScope;
import com.xz.common.constant.UserConstants;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.domain.entity.SysDept;
import com.xz.common.domain.SysAccessory;
import com.xz.common.exception.ServiceException;
import com.xz.common.service.ISysAccessoryService;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.store.Vo.*;
import com.xz.store.domain.StoreBasic;
import com.xz.store.dto.OperatingCityDto;
import com.xz.store.mapper.StoreBasicMapper;
import com.xz.store.service.IStoreBasicService;
import com.xz.system.domain.vo.DictDataVo;
import com.xz.system.mapper.SysDictDataMapper;
import com.xz.system.mapper.SysRoleMapper;
import com.xz.system.mapper.SysRoleMenuMapper;
import com.xz.system.mapper.SysTenantMapper;
import com.xz.system.service.*;
import common.PageUtil;
import common.Safes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 门店基本信息Service业务层处理
 *
 * @author xz
 * @date 2022-03-01
 */
@Service
public class StoreBasicServiceImpl extends ServiceImpl<StoreBasicMapper, StoreBasic> implements IStoreBasicService {
    @Autowired
    private StoreBasicMapper storeBasicMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysAccessoryService accessoryService;
    @Autowired
    private ISysUserService sysUserService;
    @Resource
    private SysRoleMenuMapper roleMenuMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysTenantMapper tenantMapper;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IGraphicService iGraphicService;
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private ISysTenantCommonConfigService sysTenantCommonConfigService;

    /**
     * 查询门店基本信息
     *
     * @param storeId 门店基本信息主键
     * @return 门店基本信息
     */
    @Override
    public StoreBasic selectStoreBasicByStoreId(String storeId) {
        StoreBasic storeBasic = storeBasicMapper.selectStoreBasicByStoreId(storeId);
        SysAccessory sysAccessory = new SysAccessory();
        sysAccessory.setBizId(storeBasic.getStoreId());
        sysAccessory.setBizType(3);
        sysAccessory.setFileType(1);
        List<SysAccessory> accessoryList = accessoryService.selectSysAccessoryList(sysAccessory);
        String s = accessoryList.stream().map(i -> i.getUrl()).collect(Collectors.joining(","));
        storeBasic.setStoreImage(s);
        return storeBasic;
    }

    /**
     * 查询门店基本信息列表
     *
     * @param storeBasic 门店基本信息
     * @return 门店基本信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<StoreBasic> selectStoreBasicList(StoreBasic storeBasic) {
        return storeBasicMapper.selectStoreBasicList(storeBasic);
    }

    /**
     * 门店列表（其他模块调用）
     *
     * @param storeBasic
     * @return
     */
    @DataScope(deptAlias = "d")
    public List<StoreBasicListVo> storeBasicList(StoreBasic storeBasic) {
        return storeBasicMapper.storeBasicList(storeBasic);
    }

    /**
     * 新增门店基本信息
     *
     * @param storeBasic 门店基本信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertStoreBasic(StoreBasic storeBasic) {
        if (storeBasic.getStoreType() == 1) {
            SysDept sysDept = sysDeptService.selectDeptById(Long.parseLong(storeBasic.getCompanyId()));
            //新增部门
            SysDept dept = new SysDept();
            dept.setDeptName(storeBasic.getStoreName());
            dept.setLeader(storeBasic.getContactName());
            dept.setPhone(storeBasic.getContactPhone());
            dept.setParentId(Long.parseLong(storeBasic.getCompanyId()));
            dept.setTenantId(sysDept.getTenantId());
            dept.setCreateTime(DateUtils.getNowDate());
            dept.setCreateBy(SecurityUtils.getUserId());
            int i = sysDeptService.insertDept(dept);
            if (i <= 0) {
                throw new ServiceException("添加部门失败");
            }

            //新增门店
            storeBasic.setTenantId(sysDept.getTenantId());
            storeBasic.setCompanyName(sysDept.getDeptName());
            storeBasic.setDeptId(dept.getDeptId());
        } else {
            StoreBasic basic = storeBasicMapper.selectStoreBasicByStoreId(storeBasic.getCompanyId());
            storeBasic.setTenantId(basic.getTenantId());
            storeBasic.setCompanyName(basic.getStoreName());
            storeBasic.setDeptId(basic.getDeptId());
        }
        //新增门店
        storeBasic.setStoreId("ST" + new Date().getTime());
        storeBasic.setCreateTime(DateUtils.getNowDate());
        storeBasic.setCreateBy(SecurityUtils.getUserId());
        int j = storeBasicMapper.insertStoreBasic(storeBasic);
        if (j <= 0) {
            throw new ServiceException("添加门店失败");
        }

        //保存附件
        if (StringUtils.isNotEmpty(storeBasic.getStoreImage())) {
            String[] imgarr = storeBasic.getStoreImage().split(",");
            for (String url : imgarr) {
                SysAccessory accessory = new SysAccessory(storeBasic.getStoreName() + "实景图", url, storeBasic.getStoreId(), 3, 1, storeBasic.getTenantId());
                accessory.setCreateBy(SecurityUtils.getUserId());
                accessoryService.insertSysAccessory(accessory);
            }
        }
        return j;
    }

    /**
     * 修改门店基本信息
     *
     * @param storeBasic 门店基本信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStoreBasic(StoreBasic storeBasic) {
        //修改对应部门
        StoreBasic basic = storeBasicMapper.selectStoreBasicByStoreId(storeBasic.getStoreId());
        if (storeBasic.getStoreType() == 1) {
            if (basic.getStoreType() == 1) {
                SysDept dept = sysDeptService.selectDeptById(storeBasic.getDeptId());
                dept.setDeptName(storeBasic.getStoreName());
                dept.setLeader(storeBasic.getContactName());
                dept.setPhone(storeBasic.getContactPhone());
                dept.setParentId(Long.parseLong(storeBasic.getCompanyId()));
                int i = sysDeptService.updateDept(dept);
                if (i <= 0) {
                    throw new ServiceException("修改部门失败");
                }
                storeBasic.setCompanyName(sysDeptService.selectDeptById(Long.parseLong(storeBasic.getCompanyId())).getDeptName());
            } else {
                SysDept sysDept = sysDeptService.selectDeptById(Long.parseLong(storeBasic.getCompanyId()));
                SysDept dept = new SysDept();
                dept.setDeptName(storeBasic.getStoreName());
                dept.setLeader(storeBasic.getContactName());
                dept.setPhone(storeBasic.getContactPhone());
                dept.setParentId(Long.parseLong(storeBasic.getCompanyId()));
                dept.setTenantId(sysDept.getTenantId());
                dept.setCreateTime(DateUtils.getNowDate());
                dept.setCreateBy(SecurityUtils.getUserId());
                int i = sysDeptService.insertDept(dept);
                if (i <= 0) {
                    throw new ServiceException("添加部门失败");
                }

                //新增门店
                storeBasic.setCompanyName(sysDept.getDeptName());
                storeBasic.setDeptId(dept.getDeptId());
            }

        } else {
            StoreBasic parentBasic = storeBasicMapper.selectStoreBasicByStoreId(storeBasic.getCompanyId());
            storeBasic.setCompanyName(parentBasic.getStoreName());
            storeBasic.setDeptId(parentBasic.getDeptId());
        }


        //修改门店
        storeBasic.setUpdateBy(SecurityUtils.getUserId());
        storeBasic.setUpdateTime(DateUtils.getNowDate());
        int j = storeBasicMapper.updateStoreBasic(storeBasic);
        if (j <= 0) {
            throw new ServiceException("修改门店失败");
        }
        accessoryService.deleteSysAccessoryByBizId(storeBasic.getStoreId(), 3);
        //保存附件
        if (StringUtils.isNotEmpty(storeBasic.getStoreImage())) {
            String[] imgarr = storeBasic.getStoreImage().split(",");
            for (String url : imgarr) {
                SysAccessory accessory = new SysAccessory(storeBasic.getStoreName() + "实景图", url, storeBasic.getStoreId(), 3, 1, storeBasic.getTenantId());
                accessory.setCreateBy(SecurityUtils.getUserId());
                accessoryService.insertSysAccessory(accessory);
            }
        }
        return j;
    }

    /**
     * 批量删除门店基本信息
     *
     * @param storeIds 需要删除的门店基本信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStoreBasicByStoreIds(String[] storeIds) {
        return storeBasicMapper.deleteStoreBasicByStoreIds(storeIds);
    }

    /**
     * 删除门店基本信息信息
     *
     * @param storeId 门店基本信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteStoreBasicByStoreId(String storeId) {
        StoreBasic basic = storeBasicMapper.selectStoreBasicByStoreId(storeId);
        if (basic.getStoreType() == 1) {
            //删除部门
            if (sysDeptService.hasChildByDeptId(basic.getDeptId())) {
                return AjaxResult.error("存在下级部门,不允许删除");
            }
            if (sysDeptService.checkDeptExistUser(basic.getDeptId())) {
                return AjaxResult.error("部门存在用户,不允许删除");
            }
            int j = sysDeptService.deleteDeptById(basic.getDeptId());
            if (j <= 0) {
                throw new ServiceException("删除部门失败");
            }
        }


        //删除门店
        int i = storeBasicMapper.deleteStoreBasicByStoreId(storeId);
        if (i <= 0) {
            throw new ServiceException("删除门店失败");
        }

        //删除附件
        accessoryService.deleteSysAccessoryByBizId(storeId, 3);


        return AjaxResult.success();
    }

    @Override
    @Transactional
    public int editAvailable(StoreBasic storeBasic) {
        StoreBasic basic = storeBasicMapper.selectStoreBasicByStoreId(storeBasic.getStoreId());
        if (basic.getStoreType() == 1) {
            SysDept dept = sysDeptService.selectDeptById(basic.getDeptId());
            dept.setStatus(storeBasic.getIsAvailable() == 0 ? "1" : "0");
            sysDeptService.updateDept(dept);
        }

        return storeBasicMapper.editAvailable(storeBasic);
    }

    /**
     * 运营城市下门店
     *
     * @param operatingCityDto
     * @return
     */
    public List<ClientAreaListVo> clientStoreList(OperatingCityDto operatingCityDto) {
        operatingCityDto.setPageNo(PageUtil.pageNo(operatingCityDto.getPageNo(), operatingCityDto.getPageSize() == null ? 10 : operatingCityDto.getPageSize()));
        operatingCityDto.setPageSize(operatingCityDto.getPageSize() == null ? 10 : operatingCityDto.getPageSize());
        return storeBasicMapper.clientStoreList(operatingCityDto);
    }

    /**
     * 运营城市下门店--搜索门店
     *
     * @param operatingCityDto
     * @return
     */
    public List<ClientStoreListVo> searchClientStoreList(OperatingCityDto operatingCityDto) {
        operatingCityDto.setPageNo(PageUtil.pageNo(operatingCityDto.getPageNo(), operatingCityDto.getPageSize() == null ? 10 : operatingCityDto.getPageSize()));
        operatingCityDto.setPageSize(operatingCityDto.getPageSize() == null ? 10 : operatingCityDto.getPageSize());
        return storeBasicMapper.searchClientStoreList(operatingCityDto);
    }

    /**
     * 门店下车型运营分类
     *
     * @param operatingCityDto
     * @return
     */
    @Override
    public AjaxResult classificationList(OperatingCityDto operatingCityDto) {
        if (StringUtils.isBlank(operatingCityDto.getStoreId())) {
            return AjaxResult.error("门店不能为空");
        }
        List<ClassificationListVo> classificationList = null;

        if (operatingCityDto.getBizType() == 1 || operatingCityDto.getBizType() == 3) {
            classificationList = Safes.of(storeBasicMapper.classificationList(operatingCityDto));
        } else if (operatingCityDto.getBizType() == 2) {
            classificationList = Safes.of(storeBasicMapper.longClassificationList(operatingCityDto));
        }
//        classificationList = classificationList == null ? new ArrayList<>() : classificationList;
//        if (classificationList == null || classificationList.size() == 0) {
//            return AjaxResult.success(classificationList);
//        }
        //全部车型
        ClassificationListVo classificationListVo = new ClassificationListVo();
        classificationListVo.setClassification("0");
        classificationListVo.setOperatingClassification("全部");
        List<Double> collect = classificationList.stream().map(i -> i.getMinPrice()).collect(Collectors.toList());
        Double min = CollectionUtils.isEmpty(collect)?0.0:Collections.min(collect);
        classificationListVo.setMinPrice(min);
        classificationList.add(0, classificationListVo);
        return AjaxResult.success(classificationList);
    }

    /**
     * 门店详情
     *
     * @param operatingCityDto
     * @return
     */
    public AjaxResult clientStoreInfo(OperatingCityDto operatingCityDto) {
        return AjaxResult.success(storeBasicMapper.clientStoreInfo(operatingCityDto));
    }

    /**
     * 适用门店列表
     *
     * @param tenantId
     * @return
     */
    public List<ApplicableUnitListVo> applicableUnitList(Long tenantId) {
        return baseMapper.applicableUnitList(tenantId);
    }

    @Override
    public int selectCountByCityId(Long[] ids) {
        return storeBasicMapper.selectCountByCityId(ids);
    }

    @Override
    public int selectAvailableByCityId(Long cityId) {
        return storeBasicMapper.selectAvailableByCityId(cityId);
    }

    @Override
    public String checkNameUnique(StoreBasic storeBasic) {
        String storeId = StringUtils.isNull(storeBasic.getStoreId()) ? "-1L" : storeBasic.getStoreId();
        StoreBasic info = storeBasicMapper.checkUnique(storeBasic.getStoreName());
        if (StringUtils.isNotNull(info) && !info.getStoreId().equals(storeId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 异店还车门店列表
     *
     * @return
     */
    public List<AlsoFeeStoreVo> alsoFeeStoreList() {
        return baseMapper.alsoFeeStoreList();
    }

    @Override
    public List<StoreBasic> selectAllListStore(StoreBasic storeBasic) {
        return storeBasicMapper.selectStoreBasicList(storeBasic);
    }

    //租户门店
    @DataScope(deptAlias = "d")
    public List<DictDataVo> tenantStoreList(StoreBasic storeBasic) {
        return storeBasicMapper.tenantStoreList(storeBasic);
    }

    @Override
    public String selectCurrUserStore(Long deptId) {
        return baseMapper.selectCurrUserStore(deptId);
    }

    @Override
    public List<DictDataVo> selectSeries(String storeId) {
        return baseMapper.selectSeries(storeId);
    }

    @Override
    public List<DictDataVo> selectModel(String storeId,String seriesId) {
        return baseMapper.selectModel(storeId,seriesId);
    }
    /**
     * 关联企业认证
     * @param associationEnterpriseCertificationVO
     * @return
     * @author renyong on 2023/7/18 16:06
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void associationEnterpriseCertification(AssociationEnterpriseCertificationVO associationEnterpriseCertificationVO){
        // 企业认证
        //EnterpriseCertification enterpriseCertification = associationEnterpriseCertificationVO.getEnterpriseCertification();
        Long enterpriseCertificationId = associationEnterpriseCertificationVO.getEnterpriseCertificationId();
        List<String> storeIdList = associationEnterpriseCertificationVO.getStoreIdList();
        LambdaUpdateWrapper<StoreBasic> lambdaUpdateWrapper = Wrappers.lambdaUpdate(StoreBasic.class);
        if(CollectionUtils.isEmpty(storeIdList)){
            // 关联门店id列表为空，直接清空
            lambdaUpdateWrapper.clear();
            lambdaUpdateWrapper.set(StoreBasic::getEnterpriseCertificationId,null)
                    .eq(StoreBasic::getEnterpriseCertificationId,enterpriseCertificationId);
            update(lambdaUpdateWrapper);
            return;
        }
        // 校验门店是否已被关联
        lambdaUpdateWrapper.clear();
        lambdaUpdateWrapper.ne(StoreBasic::getEnterpriseCertificationId,enterpriseCertificationId)
                .in(StoreBasic::getStoreId,storeIdList);
        List<StoreBasic> storeBasicList = list(lambdaUpdateWrapper);
        if(!CollectionUtils.isEmpty(storeBasicList)){
            String errorMsg = storeBasicList.stream()
                    .map(StoreBasic::getStoreName)
                    .collect(Collectors.joining(",", "门店:[", "]已被其他门店关联,请先解除绑定"));
            throw new ServiceException(errorMsg);
        }
        // 门店关联企业资格id清空
        lambdaUpdateWrapper.clear();
        lambdaUpdateWrapper.set(StoreBasic::getEnterpriseCertificationId,null)
                .eq(StoreBasic::getEnterpriseCertificationId,enterpriseCertificationId);
        update(lambdaUpdateWrapper);
        // 门店关联企业资格id
        lambdaUpdateWrapper.clear();
        lambdaUpdateWrapper.set(StoreBasic::getEnterpriseCertificationId,enterpriseCertificationId)
                .in(StoreBasic::getStoreId,storeIdList);
        update(lambdaUpdateWrapper);
    }
}
